package com.wx.service.impl;

import com.wx.common.SecurityUser;
import com.wx.constants.Constants;
import com.wx.entity.SysRole;
import com.wx.entity.SysUser;
import com.wx.enums.UserStatusEnum;
import com.wx.service.SysRoleService;
import com.wx.service.SysUserRoleService;
import com.wx.service.SysUserService;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>Title:	  SecurityUserDetailsService <br/> </p>
 * <p>Description TODO <br/> </p>
 * <p>Company:    医百科技有限公司  <br/> </p>
 *
 * @Author <a href="xinglinglove1029@163.com"/>杨文生</a>  <br/>
 * @Date 2018/1/16 14:45
 */
@Service
public class SecurityUserDetailsService implements UserDetailsService {

    @Resource
    private SysUserService userService;

    @Resource
    private SysUserRoleService userRoleService;

    @Resource
    private SysRoleService sysRoleService;

    @Override
    public SecurityUser loadUserByUsername(String userName) throws UsernameNotFoundException {
        SysUser user = userService.selectUserByUserName(userName);
        if (user == null) {
            throw new BadCredentialsException("用户名不存在");
        }

        if(UserStatusEnum.DISABLE.getKey() == user.getStatus()){
            throw new DisabledException("账号被禁用");
        }

        if(Constants.Sys.SUPER_MANAGER_LOGIN_NAME.equals(userName)){
            List<SysRole> sysRoles = sysRoleService.selectAll();
            List<String> roleCodes = sysRoles.stream().map(SysRole::getRoleCode).collect(Collectors.toList());
            return new SecurityUser(user,roleCodes);
        }
        List<SysRole> sysRoles = userRoleService.getBindRoleListByUserId(user.getId());
        List<String> roleCodes = sysRoles.stream().map(SysRole::getRoleCode).collect(Collectors.toList());
        return new SecurityUser(user,roleCodes);
    }
}
